{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据已成功保存至 ./2024_tenY_cdb.xlsx\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "from bs4 import BeautifulSoup\n",
    "import pandas as pd\n",
    "from datetime import datetime, timedelta\n",
    "import asyncio\n",
    "\n",
    "# 指定文件的保存目录和文件名\n",
    "file_path = './2024_tenY_cdb.xlsx'\n",
    "\n",
    "# 转成dataframe 数据格式\n",
    "data = {\n",
    "  '日期': [],\n",
    "  '10年': []\n",
    "}\n",
    "\n",
    "def save_table():\n",
    "    table_data = pd.DataFrame(data)\n",
    "    \n",
    "    # 使用to_excel方法将DataFrame保存为Excel文件\n",
    "    try:\n",
    "        table_data.to_excel(file_path, index=False)  # 设置index=False表示不保存行索引\n",
    "        print(f\"数据已成功保存至 {file_path}\")\n",
    "    except Exception as e:\n",
    "        print(f\"保存数据时出现错误: {e}\")\n",
    "\n",
    "async def set_sign_data(date):\n",
    "    # 请求参数\n",
    "    params = {\n",
    "        \"searchDate\": date\n",
    "    }\n",
    "    await asyncio.sleep(0.5)  # 避免过快发送请求\n",
    "\n",
    "    try:\n",
    "        # 发送POST请求\n",
    "        url = \"https://yield.chinabond.com.cn/gkh/yield\"\n",
    "        response = requests.post('', data=params)\n",
    "        response.raise_for_status()  # 如果请求出现错误，抛出异常\n",
    "\n",
    "        # 使用BeautifulSoup解析HTML\n",
    "        soup = BeautifulSoup(response.text, 'html.parser')\n",
    "        # 根据选择器获取元素并提取文本内容\n",
    "        element = soup.select('#conter tr:nth-child(5) td:nth-child(2)')\n",
    "        if element:\n",
    "            value = element[0].get_text(strip=True)\n",
    "            data['10年'].append(value)\n",
    "            data['日期'].append(date)\n",
    "    except requests.RequestException as e:\n",
    "        print(f\"请求出现错误: {e}\")\n",
    "\n",
    "async def set_data_by(start_date_str, end_date_str):\n",
    "    # 将输入的日期字符串转换为日期对象\n",
    "    start_date = datetime.strptime(start_date_str, '%Y%m%d')\n",
    "    end_date = datetime.strptime(end_date_str, '%Y%m%d')\n",
    "\n",
    "    # 判断开始日期是否大于等于结束日期，如果是则报错\n",
    "    if start_date >= end_date:\n",
    "        raise ValueError(\"开始日期必须小于结束日期\")\n",
    "\n",
    "    tasks = []\n",
    "    # 循环打印日期\n",
    "    current_date = start_date\n",
    "    while current_date < end_date:\n",
    "        tasks.append(set_sign_data(current_date.strftime('%Y-%m-%d')))\n",
    "        current_date += timedelta(days=1)\n",
    "    await asyncio.gather(*tasks)\n",
    "    save_table()\n",
    "\n",
    "# 获取当前日期\n",
    "end_date = datetime.now()\n",
    "end_date_str = end_date.strftime('%Y%m%d')  # 格式 20240101\n",
    "# 计算6个月前的日期（可按需调整时间范围，这里以10天为例）\n",
    "start_date = end_date - timedelta(days=10)\n",
    "start_date_str = start_date.strftime('%Y%m%d')\n",
    "\n",
    "# 如果环境中已运行事件循环\n",
    "try:\n",
    "    loop = asyncio.get_running_loop()\n",
    "except RuntimeError:\n",
    "    loop = None\n",
    "\n",
    "if loop and loop.is_running():\n",
    "    # 如果事件循环正在运行\n",
    "    task = set_data_by(start_date_str, end_date_str)\n",
    "    asyncio.ensure_future(task)  # 创建任务并调度运行\n",
    "else:\n",
    "    # 如果没有事件循环，则使用 asyncio.run()\n",
    "    asyncio.run(set_data_by(start_date_str, end_date_str))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
